import { loginData, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    getToken(stsate, data) {
      stsate.token = data
    },
    userInfo(state, data) {
      state.userInfo = data
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    removeUser(state) {
      state.userInfo = {}
    }
  },
  actions: {
    async login(ctx, res) {
      console.log(res)
      const data = await loginData(res)
      console.log(data)
      ctx.commit('getToken', data)
      setToken(data)
    },
    async getUserInfo(ctx) {
      const res = await getUserInfo()
      const resu = await getUserDetailById(res.userId)
      console.log(res, resu)
      const baseres = { ...res, ...resu }
      ctx.commit('userInfo', baseres)
    },
    logout(ctx) {
      ctx.commit('removeToken')
      ctx.commit('removeUser')
    }
  }
}
